<template>
  <div>
    <el-card shadow="never">
      <header-title title="缴费项目管理"></header-title>
    </el-card>
    <el-card shadow="never">
      <el-row :gutter="20">
        <el-col :offset="1" :span="20"></el-col>
        <el-col :span="1">
          <el-button
            @click="showAddDialog"
            class="button"
            size="small"
            round
            style="margin: 10px 0;"
          >添加缴费项目</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div style="margin: 20px 0;">
        <el-table :data="items" v-loading="loading" style="width: 100%;margin: 15px 0 25px;">
          <el-table-column prop="payTypeName" label="缴费项目"></el-table-column>
          <el-table-column prop="tempTime" label="缴费时间"></el-table-column>
          <el-table-column prop="tempPrice" label="预置单价"></el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <el-button type="text" @click="showEditDialog(scope.row)">编辑</el-button>
              <el-button
                type="text"
                :disabled="scope.row.isFixCharge==1"
                @click="removePaymentItem(scope.row.payTypeId)"
              >删除</el-button>
            </template>
          </el-table-column>
          <div slot="empty">
            <img src="../../assets/blank_tip_page/blank_tip_page.png" alt />
          </div>
        </el-table>
      </div>
    </el-card>

    <el-dialog
      width="440px"
      :title="editDialogTitle"
      :visible.sync="dialogFormVisible"
      v-if="dialogFormVisible"
    >
      <el-form :model="editModel" label-width="85px" :rules="rules" ref="editModel">
        <el-form-item label="项目名称" prop="payTypeName">
          <el-input v-model="editModel.payTypeName" :disabled="isEdit" autocomplete="off"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="单价" prop="priceYuan">
              <el-input-number v-model="editModel.priceYuan" :step="0.1" controls-position="right"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="16px" prop="unit">
              <el-select v-model="editModel.unit" placeholder="请选择">
                <el-option
                  v-for="item in paymentItemConfig.payment_unit"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="缴费时间" prop="paymentTimeType">
          <el-select v-model="editModel.paymentTimeType" placeholder="请选择">
            <el-option
              v-for="item in paymentItemConfig.payment_time_type"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-row v-if="editModel.paymentTimeType=='quarter'" key="quarter">
          <el-col :span="15">
            <el-form-item label-width="68px" label="每季度" prop="timePos">
              <el-select v-model="editModel.timePos" placeholder="每季度">
                <el-option
                  v-for="item in quarterSelectorItems"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="16px" prop="day">
              <el-input-number
                :max="31"
                v-model="editModel.day"
                controls-position="right"
                style="width:90px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="margin-top:10px">号</el-col>
        </el-row>

        <el-row v-if="editModel.paymentTimeType=='half_year'" key="half_year">
          <el-col :span="15">
            <el-form-item label-width="68px" label="每半年" prop="timePos">
              <el-select v-model="editModel.timePos" placeholder="每半年">
                <el-option
                  v-for="item in halfyearSelectorItems"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="16px" prop="day">
              <el-input-number
                :min="1"
                :max="31"
                v-model="editModel.day"
                controls-position="right"
                style="width:90px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="margin-top:10px">号</el-col>
        </el-row>

        <el-row v-if="editModel.paymentTimeType=='year'" key="year">
          <el-col :span="12">
            <el-form-item label-width="68px" label="每年" prop="month">
              <el-input-number
                :min="1"
                :max="12"
                v-model="editModel.month"
                controls-position="right"
                style="width:110px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label-width="36px" label="月" prop="day">
              <el-input-number
                :min="1"
                :max="31"
                v-model="editModel.day"
                controls-position="right"
                style="width:110px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="margin-top:10px">号</el-col>
        </el-row>

        <el-row v-if="editModel.paymentTimeType=='month'" key="month">
          <el-col :span="12">
            <el-form-item label-width="68px" label="每月" prop="day">
              <el-input-number
                :min="1"
                :max="31"
                v-model="editModel.day"
                controls-position="right"
                style="width:110px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="margin-top:10px">号</el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('editModel')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import HeaderTitle from "@/components/HeaderTitle";
import CountUp from "@/components/CountUp/index";
import CardItem from "@/components/CardItem/index.vue";
import { formatDate, formatDate2, isNil } from "@/utils";
export default {
  name: "PurchaseInfo",
  components: {
    HeaderTitle,
    CountUp,
    CardItem
  },
  data() {
    return {
      items: [],
      meatPage: {
        perPage: 10, // 每页显示10条
        page: 1, // 当前页
        total: 0
      },
      loading: true,
      upperReaches: {},
      newRecallModel: {},
      paymentItemConfig: {
        payment_unit: []
      },
      quarterSelectorItems: [],
      halfyearSelectorItems: [],
      dialogFormVisible: false,
      isEdit: false,
      editDialogTitle: "添加缴费项目",
      editModel: {
        paymentTimeType: "",
        priceYuan: ""
      },
      rules: {
        payTypeName: [
          { required: true, message: "请输入项目名称", trigger: "blur" }
        ],
        priceYuan: [
          { required: true, message: "请输入单价", trigger: "change" }
        ],
        unit: [{ required: true, message: "请选择单位", trigger: "change" }],
        paymentTimeType: [
          { required: true, message: "请选择缴费时间", trigger: "change" }
        ],
        timePos: [
          { required: true, message: "请选择时间范围", trigger: "change" }
        ],
        day: [{ required: true, message: "请选择几号", trigger: "change" }],
        month: [{ required: true, message: "请选择第几月", trigger: "change" }]
      }
    };
  },
  watch: {
    "$store.state.app.marketId"(val, oldVal) {
      this.fetchPaymentItems();
      this.fetchPaymentItemConfig();
    }
  },
  mounted() {
    this.fetchPaymentItems();
    this.fetchPaymentItemConfig();
  },
  methods: {
    defaultValue(value, defaultValue) {
      if (isNil(value)) {
        return defaultValue;
      }
      return value;
    },

    fetchPaymentItems() {
      this.$store
        .dispatch("paymentItem/fetchPaymentItems")
        .then(data => {
          this.loading = false;
          this.items = [];
          for (var item of data.data) {
            item.tempPrice = item.price / 100 + item.unit;
            if (item.paymentTimeType == "month") {
              item.tempTime = "每月 " + item.day + " 日缴费";
            } else if (item.paymentTimeType == "quarter") {
              item.tempTime =
                "每季度 " + item.months + " 月" + item.day + " 日缴费";
            } else if (item.paymentTimeType == "half_year") {
              item.tempTime =
                "每年 " + item.months + " 月" + item.day + " 日缴费";
            } else if (item.paymentTimeType == "year") {
              item.tempTime =
                "每年 " + item.months + " 月" + item.day + " 日缴费";
            }
            this.items.push(item);
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },

    fetchPaymentItemConfig() {
      this.$store
        .dispatch("paymentItem/fetchPaymentItemConfig")
        .then(data => {
          this.paymentItemConfig = data.data;
          console.log("paymentItemConfig", this.paymentItemConfig);
          this.quarterSelectorItems = [];
          this.halfyearSelectorItems = [];
          for (let pos of this.paymentItemConfig.payment_time_pos) {
            let quarterIndexName = "quarter_" + pos.id;
            let halfyearIndexName = "half_year_" + pos.id;
            let quarterSelectorItem = {
              id: pos.id,
              name:
                pos.name +
                "（" +
                this.paymentItemConfig.payment_time_type_select[
                  quarterIndexName
                ] +
                "月）"
            };
            let halfyearSelectorItem = {
              id: pos.id,
              name:
                pos.name +
                "（" +
                this.paymentItemConfig.payment_time_type_select[
                  halfyearIndexName
                ] +
                "月）"
            };
            this.halfyearSelectorItems.push(halfyearSelectorItem);
            this.quarterSelectorItems.push(quarterSelectorItem);
          }

          console.log("paymentItemConfig", this.halfyearSelectorItems);

          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
        });
    },

    removePaymentItem(id) {
      this.$store
        .dispatch("paymentItem/remove", id)
        .then(data => {
          console.log(data);
          this.fetchPaymentItems();
        })
        .catch(err => {
          this.loading = false;
        });
    },

    showEditDialog(data) {
      this.editDialogTitle = "编辑缴费项目";
      this.isEdit = true;
      this.dialogFormVisible = true;
      console.log("编辑");
      let obj = { priceYuan: "" };
      data = { ...obj, ...data };
      this.editModel = data;
      this.editModel.priceYuan = this.editModel.price / 100;
      this.editModel.timePos = this.editModel.timePos + "";
    },

    showAddDialog(data) {
      this.editModel = {};
      this.editDialogTitle = "添加缴费项目";
      this.isEdit = false;
      this.dialogFormVisible = true;
    },

    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.editModel.paymentTimeType == "month") {
            console.log("go this");
            this.editModel.months = 0;
          } else if (this.editModel.paymentTimeType == "quarter") {
            let index = "quarter_" + this.editModel.timePos;
            this.editModel.months = this.paymentItemConfig.payment_time_type_select[
              index
            ];
          } else if (this.editModel.paymentTimeType == "half_year") {
            let index = "half_year_" + this.editModel.timePos;
            this.editModel.months = this.paymentItemConfig.payment_time_type_select[
              index
            ];
          } else if (this.editModel.paymentTimeType == "year") {
            this.editModel.months = this.editModel.month;
          }
          console.log(
            "payment_time_type",
            this.paymentItemConfig.payment_time_type
          );

          for (const type of this.paymentItemConfig.payment_time_type) {
            if (type.id == this.editModel.paymentTimeType) {
              this.editModel.paymentTimeTypeName = type.name;
              break;
            }
          }

          this.editModel.price = this.editModel.priceYuan * 100;

          if (this.isEdit) {
            this.$store
              .dispatch("paymentItem/edit", this.editModel)
              .then(data => {
                console.log(data);
                this.fetchPaymentItems();
                this.dialogFormVisible = false;
              })
              .catch(err => {
                this.loading = false;
              });
          } else {
            this.$store
              .dispatch("paymentItem/add", this.editModel)
              .then(data => {
                console.log(data);
                this.fetchPaymentItems();
                this.dialogFormVisible = false;
              })
              .catch(err => {
                this.loading = false;
              });
          }
          console.log("editModel", this.editModel);
        } else {
          this.$message.error("必填项未填");
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table__empty-text {
  width: 100%;
}
#detail-dialog {
  .ptitle {
    color: #00cbe4;
    font-size: 16px;
  }
  .pnumber {
    margin: 15px 10px;
    font-size: 14px;
  }
  /deep/.el-dialog__body {
    padding: 0px 20px 30px;
    color: #606266;
    font-size: 14px;
  }
  /deep/.el-card__header {
    padding: 10px 20px 0;
    border-bottom: 1px solid #ebeef5;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
}
</style>
